package com.hhp.hhptt.utils;

import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.hhp.hhptt.entity.User;
import com.hhp.hhptt.service.UserService;
import com.hhp.hhptt.service.impl.UserServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class TokenUtils {



    @Autowired
    UserService userService;



    /**
     * 设置token的秘钥
     */
    private static final String TOKEN_SECRET = "my_secret_key";
    public static String getToken(String userId,String sign){

        Map<String, Object> head = new HashMap<>();
        head.put("typ", "JWT");
        head.put("alg", "HS256");
        // 设置秘钥
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        String token = JWT.create().withHeader(head).withAudience(userId)
//        String token = JWT.create().withAudience(userId)
                .withExpiresAt(DateUtil.offsetHour(new Date(),24)) //2小时后token过期
//                .sign(Algorithm.HMAC256(sign));
                .sign(algorithm);
        return token;

    }

    public  User getCurrentUser(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if(!StringUtils.isBlank(token)){
                String userId = JWT.decode(token).getAudience().get(0);
                return userService.getById(userId);
            }
        } catch (JWTDecodeException e) {
//            throw new RuntimeException(e);
            return null;
        }
      return null;
    }
}
